package com.lekang.system.task;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import com.lekang.system.service.IAppointmentRegistrationService;

import java.time.LocalTime;
import java.time.LocalDateTime;

/**
 * 预约过期处理定时任务
 * 
 * @author 刘卓
 * @date 2025-10-13
 */
@Component
public class AppointmentExpireTask
{
    private static final Logger log = LoggerFactory.getLogger(AppointmentExpireTask.class);

    @Autowired
    private IAppointmentRegistrationService appointmentRegistrationService;


//    @Scheduled(cron = "0/10 * * * * ?")  // 每10秒执行一次
//    @Scheduled(cron = "1 0/30 8-19 * * ?")  // 生产环境：每30分钟执行
    public void expireOvertimeAppointments()
    {
        try
        {
            // 检查当前时间是否在工作时间范围内
            LocalTime currentTime = LocalTime.now();
            LocalTime startTime = LocalTime.of(8, 0);
            LocalTime endTime = LocalTime.of(19, 0);
            
            if (currentTime.isBefore(startTime) || currentTime.isAfter(endTime))
            {
                log.info("当前时间不在工作时间范围内(8:00-19:00)，跳过预约过期处理");
                return;
            }
            
            log.info("开始执行预约过期处理定时任务，当前时间：{}", LocalDateTime.now());
            
            int expiredCount = appointmentRegistrationService.expireOvertime();
            
            if (expiredCount > 0)
            {
                log.info("预约过期处理完成，共处理 {} 条过期预约记录", expiredCount);
            }
            else
            {
                log.info("预约过期处理完成，没有需要处理的过期预约记录");
            }
        }
        catch (Exception e)
        {
            log.error("预约过期处理定时任务执行失败", e);
        }
    }

    /**
     * 手动触发过期处理（用于测试）
     */
    public void manualExpireOvertime()
    {
        log.info("手动触发预约过期处理");
        expireOvertimeAppointments();
    }
}